package com.xiaobai;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

interface Cat {
    void run();
}

public class CglibProxy {
    public static void main(String[] args) {
        // 代理对象
        Cat proxy = (Cat) new MyMethodInterceptor().getProxyObject(new BlackCat());
        // 执行代理对象的方法
        proxy.run();
        System.out.println();
        // 代理对象
        Cat proxy1 = (Cat) new MyMethodInterceptor().getProxyObject(new WhiteCat());
        // 执行代理对象的方法
        proxy1.run();

    }
}

class BlackCat implements Cat {
    @Override
    public void run() {
        System.out.println("黑猫在跑");
    }
}

class WhiteCat implements Cat {
    @Override
    public void run() {
        System.out.println("白猫在跑");
    }
}

class MyMethodInterceptor implements MethodInterceptor {

    // 被代理的目标对象
    private Object target;

    public Object getProxyObject(Object target) {
        this.target = target;
        // 增强器，动态代码生成器
        Enhancer enhancer = new Enhancer();
        // 回调方法
        enhancer.setCallback(this);
        // 设置生成代理类的父类类型
        enhancer.setSuperclass(target.getClass());
        // 动态生成字节码并返回代理对象
        return enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object result = methodProxy.invoke(target, objects);
        after();
        return result;

    }

    public void before() {
        System.out.println("我去追");
    }

    public void after() {
        System.out.println("不追了");
    }
}
